package com.flashidea.zddziot.activity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.content.*;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.*;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;

import com.flashidea.zddziot.R;
import com.flashidea.zddziot.utlis.BluetoothChatService;
import com.flashidea.zddziot.utlis.CMDUtils;
import com.flashidea.zddziot.view.*;
import com.flashidea.zddziot.view.RateSeekBarView.OnRateChangeListener;
import com.flashidea.zddziot.view.RoundAnimView.OnRoundItemClickListener;

@SuppressWarnings("deprecation")
public class MainActivity extends BluetoothChatActivity implements OnClickListener {

	public static final String PREF_CONFIG = "config";
	public static final String CONNECTING_DEVICE = "connecting_device";
	private static final String TAG = "MainActivity";
	protected static final String PREF_VOL_KEY = "vol_angle";
	private static final String VOICE_FREQUENCYS = "voice_frequencys";
	private static final String PREF_FM_COLETION = "pref_fm_coletion";
	private Button btnEq;
	/**
	 * 静音
	 */
	private ImageButton ibtnMute;
	/**
	 * 上一首
	 */
	private Button btnPrevious;
	/**
	 * 下一首
	 */
	private Button btnNext;
	/**
	 * 暂停与播放
	 */
	private ImageButton ibtnPlayPause;
	private RoundAnimView roundmenu;
	private ArrayList<Object> menuOneLevel;
	private HashMap<Object, List<Object>> menuTwoLevel;
	private List<String> eqList;
	/**
	 * 电源开关
	 */
	private ImageView ivPower;
	private SharedPreferences sp;
	/**
	 * 添加音频按钮
	 */
	private ImageButton btnAdd;
	/**
	 * 收藏的频率集合
	 */
	private List<String> frequencys;
	/**
	 * 进度条
	 */
	private SmileSeekBarView seekBar;
	private String leftText;
	private String rightText;
	private TextView tvMode;
	private TextView tvVol;
	private TextView tvDevice;
	private TextView tvSoundEffect;
	private TextView tvInfo;
	private TextView tvPlayType;
	private int currEQ;
	private int currVol;
	private int currAngle;
	private final String PREF_EQ_KEY = "currEQ";
	private String NULL_VALUE = "- - -";
	private String NULL_TIME = "- - : - -";
	/**
	 * 收音频率调节器
	 */
	private RateSeekBarView rateSeekBarView;
	private String musicName = "";
	private float FmValue;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		sp = getSharedPreferences(PREF_CONFIG, Context.MODE_PRIVATE);
	}

	/**
	 * 初始化状态信息
	 */
	private void initStateInfo() {
		initEQ(sp.getInt(PREF_EQ_KEY, 0));
		roundmenu.setAngle(sp.getInt(PREF_VOL_KEY, -90));
		initFMColetion();
	}

	private void initFMColetion() {
		String coletion = sp.getString(PREF_FM_COLETION, null);
		if (coletion != null) {
			if (D)
				Log.i(TAG, "FM coletion : " + coletion); // [102.5, 104.2,
															// 105.5]
			String[] split = coletion.replace("[", "").replace("]", "").split(", ");
			for (int i = 0; i < split.length; i++) {
				frequencys.add(split[i]);
			}
			refreshFrequencyLayout();
		}
	}

	private void initEQ(int count) {
		// EQ
		String eq = eqList.get(count);
		btnEq.setText(eq);
		tvSoundEffect.setText(eq);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Editor edit = sp.edit();
		// 保存收藏FM
		String fmColetion = getFMColetion();
		edit.putString(PREF_FM_COLETION, fmColetion);
		// 保存EQ
		edit.putInt(PREF_EQ_KEY, currEQ);
		// 音量
		edit.putInt(PREF_VOL_KEY, currAngle);
		edit.commit();
		if (super.mChatService != null)
			super.mChatService.stop();
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	private String getFMColetion() {
		if (frequencys.size() < 1) {
			return null;
		}
		String arrStr = frequencys.toString(); // [99.0, 100.5, 102.0, 103.3]
		if (D)
			Log.i(TAG, arrStr);
		return arrStr;
	}

	/**
	 * 初始化视图
	 */
	@SuppressWarnings("deprecation")
	@Override
	protected void initView() {
		btnEq = (Button) findViewById(R.id.btn_eq);
		btnEq.setOnClickListener(this);
		eqList = Arrays.asList(getResources().getStringArray(R.array.eq));
		btnEq.setText(eqList.get(0));
		ivPower = (ImageView) findViewById(R.id.iv_power);
		ivPower.setOnClickListener(this);
		ibtnMute = (ImageButton) findViewById(R.id.ibtn_mute);
		ibtnMute.setOnClickListener(this);
		btnPrevious = (Button) findViewById(R.id.btn_previous);
		btnPrevious.setOnClickListener(this);
		btnNext = (Button) findViewById(R.id.btn_next);
		btnNext.setOnClickListener(this);
		btnAdd = (ImageButton) findViewById(R.id.btn_add);
		btnAdd.setOnClickListener(this);
		ibtnPlayPause = (ImageButton) findViewById(R.id.ibtn_play_pause);
		ibtnPlayPause.setOnClickListener(this);
		ll_bottom_play = (LinearLayout) findViewById(R.id.lly_bottom_play);
		tv_handle = (TextView) findViewById(R.id.tv_coletion_handle);
		sd_preselect = (SlidingDrawer) findViewById(R.id.sd_main_fm_coletion);
		sd_preselect.setOnDrawerOpenListener(new OnDrawerOpenListener() {

			@Override
			public void onDrawerOpened() {
				tv_handle.setText(getResources().getString(R.string.long_press_to_delete));
				refreshFrequencyLayout();
			}
		});
		sd_preselect.setOnDrawerCloseListener(new OnDrawerCloseListener() {

			@Override
			public void onDrawerClosed() {
				tv_handle.setText(getResources().getString(R.string.my_collection));
			}
		});
		ll_times = (LinearLayout) findViewById(R.id.ll_main_music_times);
		tv_curr_time = (TextView) findViewById(R.id.tv_main_curr_time);
		tv_total_time = (TextView) findViewById(R.id.tv_main_total_time);
		// 显示区
		tvMode = (TextView) findViewById(R.id.tv_mode);
		tvVol = (TextView) findViewById(R.id.tv_main_vol);
		tvDevice = (TextView) findViewById(R.id.tv_main_device);
		tvSoundEffect = (TextView) findViewById(R.id.tv_main_sound_effect);
		tvInfo = (TextView) findViewById(R.id.tv_main_info);
		tvPlayType = (TextView) findViewById(R.id.tv_main_play_type);
		roundmenu = (RoundAnimView) findViewById(R.id.roundmenu);
		// 设置旋转菜单点击事件
		roundmenu.setOnRoundItemClickListener(new OnRoundItemClickListener() {

			@Override
			public void onRoundItemClick(int parentPosition, Object parent, int position,
					Object clichMenu) {
				if (position != -1) {
					Object menu;
					if (parentPosition != -1) {
						menu = menuTwoLevel.get(menuOneLevel.get(parentPosition)).get(position);
					} else {
						menu = menuOneLevel.get(position);
					}
					String action = menu.toString();
					Log.i(TAG, action);
					disposeRoundClick(action);
				}
			}
		});
		// 设置音量调节监听
		roundmenu.setOnAngleChangeListener(new OnAngleChangeListener() {

			@Override
			public void onAngleChange(Object view, int viewId, int angle, int degree) {
				if (Math.abs(angle - currAngle) >= 6) { // 6个角度发送一次
					String messsage;
					if(angle - currAngle > 0){ //
						messsage = CMDUtils.VOL_CLOCKWISE;
					}else{
						messsage = CMDUtils.VOL_COUNTERCLOCKWISE;
					}
					currAngle = angle;
					// 每给两个角度发一次指令
					sendMessage(messsage);
					if (D)
						Log.i(TAG, "角度 ：" + angle + " ," + degree);
				}
			}
		});
		// 播放进度条
		seekBar = (SmileSeekBarView) findViewById(R.id.smileSeekBarView);
		leftText = CMDUtils.readMusicTime("AT#28075 53");
		rightText = CMDUtils.readMusicTime("AT#28075 53");
//		seekBar.setLeftText(leftText);
//		seekBar.setRightText(rightText);
		seekBar.setProgress(0);
		seekBar.setTouch(false);// 设置不可拖动，设置为可以拖动时才会有监听回调
		// 收音调节器
		rateSeekBarView = (RateSeekBarView) findViewById(R.id.rateSeekBarView);
		rateSeekBarView.setOnRateChangeListener(new OnRateChangeListener() {

			@Override
			public void onRateChange(Object view, int viewId, float value) {
				if (rateSeekBarView.getVisibility() == View.VISIBLE) {
					if (isRadioModel) {
						String result = String.valueOf(value);
						tvInfo.setText("FM\t" + result);
						MainActivity.this.FmValue = value;
						if (D)
							Log.i(TAG, "changed fmvalue : " + value);
//						sendMessage(fmcmd);
					}
				}
			}
		});
		rateSeekBarView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (D)
					Log.i(TAG, "onTouch");
				switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						break;
					case MotionEvent.ACTION_MOVE:
						break;
					case MotionEvent.ACTION_UP:  // 在松开手时才发送命令
						String fmcmd = CMDUtils.getFMCMD(MainActivity.this.FmValue);
						if (D)
							Log.i(TAG, "Send fmcmd : " + fmcmd);
						sendMessage(fmcmd);
						break;
					default:
						break;
				}
				return false;
			}
		});
		changeModel(false);
		initData();
		//
		initStateInfo();
	}

	/**
	 * 处理音量调节按钮点击事件
	 */
	private void disposeRoundClick(String action) {
		if (action.equals("音效")) {
			roundmenu.closeMenu();
			Intent intent = new Intent(MainActivity.this, SoundEffectActivity.class);
			startActivity(intent);
		} else if (action.equals("时钟")) {
			// 发送时间同步命令
			sendMessage(CMDUtils.getCurrTimeCMD());
			Toast.makeText(getApplicationContext(), "时间已同步", 0).show();
			roundmenu.closeMenu();
		} else if (action.equals("LIGHT")) {
			Intent intent = new Intent(MainActivity.this, LightColorActivity.class);
			startActivity(intent);
		} else if (action.equals("RADIO") || action.equals("USB") || action.equals("SD")
			|| action.equals("AUX") || action.equals("BT")) {
			tvMode.setText(action);
			if (action.equals("RADIO")) {
				changeModel(true);
				sendMessage(CMDUtils.RADIO);
				ll_times.setVisibility(View.INVISIBLE);
			} else {
				changeModel(false);
				ll_times.setVisibility(View.VISIBLE);
			}
			if (action.equals("AUX")) {
				btnPrevious.setEnabled(false);
				btnNext.setEnabled(false);
				ibtnPlayPause.setEnabled(false);
				ll_times.setVisibility(View.INVISIBLE);
				tvInfo.setText(NULL_VALUE);
				sendMessage(CMDUtils.AUX);
			} else {
				btnPrevious.setEnabled(true);
				btnNext.setEnabled(true);
				if (action.equals("RADIO")) {
					ibtnPlayPause.setEnabled(false);
					ll_times.setVisibility(View.INVISIBLE);
				} else {
					ibtnPlayPause.setEnabled(true);
					ll_times.setVisibility(View.VISIBLE);
				}
			}
			if (action.equals("BT")) {
//				Intent intent = new Intent(Intent.ACTION_MAIN);
//				intent.addCategory(Intent.CATEGORY_APP_MUSIC);
//				startActivity(intent);
				sendMessage(CMDUtils.BT);
			} else if (action.equals("USB")) {
				sendMessage(CMDUtils.USB);
			} else if (action.equals("SD")) {
				sendMessage(CMDUtils.SD);
			}
		} else if (action.equals("RDM")) {
			sendMessage(CMDUtils.RDM);
			tvPlayType.setText(action);
		} else if (action.equals("RPT")) {
			sendMessage(CMDUtils.RPT);
			tvPlayType.setText(action);
		} else if (action.equals("ALL")) {
			sendMessage(CMDUtils.ALL);
			tvPlayType.setText(action);
		} else if (action.equals("时钟")) {
			sendMessage(CMDUtils.getCurrTimeCMD());
			Toast.makeText(getApplicationContext(), "时间已同步", 0).show();
			roundmenu.closeMenu();
		} else if (action.equals(getResources().getString(R.string.secure_connect))) {
			startDeviceListActivity(REQUEST_CONNECT_DEVICE_INSECURE);
			roundmenu.closeMenu();
		} else if (action.equals(getResources().getString(R.string.bluetooth_setting))) {
			startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
			roundmenu.closeMenu();
		} else {
			Toast.makeText(getApplicationContext(), action, 0).show();
		}
	}

	/**
	 * 改变模式
	 * 
	 * @param isRadioModel
	 *            是否收音模式
	 */
	private void changeModel(boolean isRadioModel) {
		// this.leftText = leftText;
		// this.rightText = rightText;
		// seekBar.setLeftText(leftText);
		// seekBar.setRightText(rightText);
		// seekBar.setCarveLine(isCarveLine);
		if (isRadioModel) {
			rateSeekBarView.setVisibility(View.VISIBLE);
			seekBar.setVisibility(View.GONE);
			sd_preselect.setVisibility(View.VISIBLE);
			ibtnPlayPause.setEnabled(false);
			ll_times.setVisibility(View.INVISIBLE);
			tvInfo.setText("FM\t" + String.valueOf(rateSeekBarView.getRate()));
		} else {
			rateSeekBarView.setVisibility(View.GONE);
			seekBar.setVisibility(View.VISIBLE);
			sd_preselect.setVisibility(View.INVISIBLE);
			ibtnPlayPause.setEnabled(true);
			ll_times.setVisibility(View.VISIBLE);
			tvInfo.setText(NULL_VALUE);
		}
		this.isRadioModel = isRadioModel;
	}

	private boolean isRadioModel;
	/**
	 * 底部播放控件栏
	 */
	private LinearLayout ll_bottom_play;
	/**
	 * 预选的fm频道
	 */
	private SlidingDrawer sd_preselect;
	private LinearLayout ll_times;
	private TextView tv_curr_time;
	private TextView tv_total_time;
	private TextView tv_handle;
	/**
	 * 当前不放时间
	 */
	private int currTime = 0;
	/**
	 * 当前音乐的总时间
	 */
	private int totalTime = 0;

	/**
	 * 初始化数据
	 */
	private void initData() {
		// ********************添加旋转菜单项******************
		menuOneLevel = new ArrayList<Object>();
		menuOneLevel.add("模式");
		menuOneLevel.add("时钟");
		menuOneLevel.add("播放");
		menuOneLevel.add("音效");
		menuOneLevel.add(getResources().getString(R.string.secure_connect));
		menuOneLevel.add(getResources().getString(R.string.bluetooth_setting));
		menuTwoLevel = new HashMap<Object, List<Object>>();
		List<Object> list = new ArrayList<Object>();
		list.add("USB");
		list.add("RADIO");
		list.add("AUX");
		list.add("BT");
		list.add("LIGHT");
		list.add("SD");
		menuTwoLevel.put(menuOneLevel.get(0), list);
		list = new ArrayList<Object>();
		list.add("RDM");
		list.add("RPT");
		list.add("ALL");
		menuTwoLevel.put(menuOneLevel.get(2), list);
		roundmenu.setMenuOneLevel(menuOneLevel);
		roundmenu.setMenuTwoLevel(menuTwoLevel);
		// ********************添加旋转菜单项******************
		// 初始化收藏的频率集合
		frequencys = new ArrayList<String>();
	}

	@Override
	protected synchronized void onResume() {
		super.onResume();
		// API>9
		// Set<String> stringSet = sp.getStringSet(VOICE_FREQUENCYS, null);
		// if (stringSet != null && !stringSet.isEmpty()) {
		// for (String key : stringSet) {
		// addVoiceFrequency(key);
		// }
		// }
	}

	@Override
	public void onClick(View v) {
		int level;
		switch (v.getId()) {
			case R.id.btn_eq:
				int count = (eqList.indexOf(btnEq.getText().toString()) + 1) % eqList.size();
				btnEq.setText(eqList.get(count));
				SendEQ(count);
				break;
			case R.id.ibtn_mute:
				level = ibtnMute.getDrawable().getLevel();
				if (level == 0) {
					ibtnMute.getDrawable().setLevel(1);
					sendMessage(CMDUtils.MUTEON);
				} else {
					ibtnMute.getDrawable().setLevel(0);
					sendMessage(CMDUtils.MUTEOFF);
				}
				break;
			case R.id.iv_power:
				level = ivPower.getBackground().getLevel();
				if (level == 0) {
					ivPower.getBackground().setLevel(1);
					sendMessage(CMDUtils.POWERON);
				} else {
					ivPower.getBackground().setLevel(0);
					sendMessage(CMDUtils.POWEROFF);
				}
				break;
			case R.id.btn_previous:
				if (isRadioModel) {
					rateSeekBarView.lastChannel();
				} else {
					sendMessage(CMDUtils.PREV);
				}
				break;
			case R.id.btn_next:
				if (isRadioModel) {
					rateSeekBarView.nextChannel();
				} else {
					sendMessage(CMDUtils.NEXT);
				}
				break;
			case R.id.ibtn_play_pause:
				level = ibtnPlayPause.getBackground().getLevel();
				if (level == 0) {
					ibtnPlayPause.getBackground().setLevel(1);
					sendMessage(CMDUtils.PLAY);
				} else {
					ibtnPlayPause.getBackground().setLevel(0);
					sendMessage(CMDUtils.PAUSE);
				}
				break;
			case R.id.btn_add:
				addVoiceFrequency(rateSeekBarView.getRate() + "");
				break;
		}
	}

	/**
	 * 添加收藏音频
	 * 
	 * @param frequency
	 */
	private void addVoiceFrequency(String frequency) {
		if (frequencys.contains(frequency)) {
			Toast.makeText(MainActivity.this, "您已收藏该频道", Toast.LENGTH_SHORT).show();
			return;
		}
		if (frequencys.size() < 8) {
			frequencys.add(frequency);
			// API>9
			// sp.edit().putStringSet(VOICE_FREQUENCYS,
			// frequencys.keySet()).commit();
		}
		refreshFrequencyLayout();
	}

	private View getButton(String frequency) {
		View inflate = View.inflate(this, R.layout.item_coletion, null);
		Button child = (Button) inflate.findViewById(R.id.btn_coletion);
		child.setText(frequency);
		child.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String fm = ((Button) v).getText().toString();
				sendMessage(CMDUtils.getFMCMD(Float.parseFloat(fm)));
				rateSeekBarView.setRate(Float.valueOf(fm));
			}
		});
		child.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				String fm = ((Button) v).getText().toString();
				frequencys.remove(fm);
				refreshFrequencyLayout();
				Toast.makeText(MainActivity.this, "已删除收藏", Toast.LENGTH_SHORT).show();
				return true;
			}
		});
		return inflate;
	}

	/**
	 * 刷新频率Layout
	 */
	private void refreshFrequencyLayout() {
		if (D)
			Log.i(TAG, frequencys.toString());
		LinearLayout lly_add = (LinearLayout) findViewById(R.id.lly_add);
		lly_add.removeAllViews();
		for (String fm : frequencys) {
			lly_add.addView(getButton(fm));
		}
		if (frequencys.size() < 8) {
			btnAdd.setVisibility(View.VISIBLE);
		} else {
			btnAdd.setVisibility(View.GONE);
		}
	}

	private void SendEQ(int count) {
		currEQ = count;
		switch (count) {
			case 0:
				sendMessage(CMDUtils.EQ_NOR);
				tvSoundEffect.setText("NOR");
				break;
			case 1:
				sendMessage(CMDUtils.EQ_POP);
				tvSoundEffect.setText("POP");
				break;
			case 2:
				sendMessage(CMDUtils.EQ_ROCK);
				tvSoundEffect.setText("ROCK");
				break;
			case 3:
				sendMessage(CMDUtils.EQ_JAZZ);
				tvSoundEffect.setText("JAZZ");
				break;
			case 4:
				sendMessage(CMDUtils.EQ_CLASS);
				tvSoundEffect.setText("CLASS");
				break;
			default:
				break;
		}
	}

	/**
	 * 当蓝牙服务状态发生改变时
	 */
	@Override
	protected void onBluetoothChatStateChange(int state) {
		switch (state) {
			case BluetoothChatService.STATE_CONNECTED:
				tvDevice.setText(getmConnectedDeviceName());
				Toast.makeText(this, getResources().getString(R.string.connection_successful),
					Toast.LENGTH_SHORT).show();
				sendMessage(CMDUtils.SYNC);
				break;
			case BluetoothChatService.STATE_CONNECTING:
				tvDevice.setText(getResources().getString(R.string.title_connecting));
				break;
			case BluetoothChatService.STATE_LISTEN:
				tvDevice.setText(getResources().getString(R.string.not_connected));
				break;
			case BluetoothChatService.STATE_NONE:
				tvDevice.setText(getResources().getString(R.string.none_paired));
				break;
			default:
				break;
		}
	}

	/**
	 * 当发送指令后
	 */
	@Override
	protected void onAfterWriteMessage(String writeMessage) {
	}

	/**
	 * 当连接的设备发送改变时
	 */
	@Override
	protected void onConnectedDeviceNameChange(String mConnectedDeviceName2) {
		tvDevice.setText(mConnectedDeviceName2);
	}

	/**
	 * 当接收到来自已连接的蓝牙设备的信息
	 */
	@Override
	protected void onReadMessage(String readMessage) {
		if (readMessage.startsWith(CMDUtils.READ_VOL_HEAD)) {
			tvVol.setText(String.valueOf(CMDUtils.getVolValue(readMessage)));
		} else if (readMessage.startsWith(CMDUtils.FM_HEAD)) {
			float fmVlaue = CMDUtils.getFmVlaue(readMessage);
			// 设置当前频率
			rateSeekBarView.setRate(fmVlaue);
			if (isRadioModel) {
				tvInfo.setText("FM\t" + String.valueOf(fmVlaue));
			}
		} else if (readMessage.startsWith(CMDUtils.EQ)) {
			int count = CMDUtils.getEqValue(readMessage);
			String eq = eqList.get(count);
			btnEq.setText(eq);
			tvSoundEffect.setText(eq);
		} else if (readMessage.startsWith(CMDUtils.POWEROFF)) {
			ivPower.getBackground().setLevel(0);
		} else if (readMessage.startsWith(CMDUtils.POWERON)
			|| readMessage.equals(CMDUtils.ON_POWERON)) {
			ivPower.getBackground().setLevel(1);
		} else if (readMessage.startsWith(CMDUtils.MUTEOFF)
			|| readMessage.equals(CMDUtils.ON_POWEROFF)) {
			ibtnMute.getDrawable().setLevel(0);
		} else if (readMessage.startsWith(CMDUtils.MUTEON)) {
			ibtnMute.getDrawable().setLevel(1);
		} else if (readMessage.equals(CMDUtils.RADIO) || readMessage.equals(CMDUtils.USB)
			|| readMessage.equals(CMDUtils.SD) || readMessage.equals(CMDUtils.AUX)
			|| readMessage.equals(CMDUtils.BT)) {
			if (readMessage.equals(CMDUtils.RADIO)) {
				changeModel(true);
				tvMode.setText("RADIO");
				ibtnPlayPause.setEnabled(false);
			} else {
				changeModel(false);
				ibtnPlayPause.setEnabled(true);
				if (readMessage.equals(CMDUtils.AUX)) {
					btnPrevious.setEnabled(false);
					btnNext.setEnabled(false);
					ibtnPlayPause.setEnabled(false);
					tv_total_time.setText(NULL_TIME);
					tv_curr_time.setText(NULL_TIME);
					seekBar.setProgress(0);
					tvMode.setText("AUX");
				} else {
					btnPrevious.setEnabled(true);
					btnNext.setEnabled(true);
					if (readMessage.equals(CMDUtils.BT)) {
						tvMode.setText("BT");
						tv_total_time.setText(NULL_TIME);
						tv_curr_time.setText(NULL_TIME);
						seekBar.setProgress(0);
					} else if (readMessage.equals(CMDUtils.USB)) {
						tvMode.setText("USB");
					} else if (readMessage.equals(CMDUtils.SD)) {
						tvMode.setText("SD");
					}
				}
			}
		} else if (readMessage.equals(CMDUtils.RDM)) {
			tvPlayType.setText("RDM");
		} else if (readMessage.equals(CMDUtils.ALL)) {
			tvPlayType.setText("ALL");
		} else if (readMessage.equals(CMDUtils.RPT)) {
			tvPlayType.setText("RPT");
		} else if (readMessage.startsWith(CMDUtils.MUSIC_NAME_HEAD)) { // 歌名信息
			try {
				musicName = getMusicName(readMessage, CMDUtils.getMusicEncoding(readMessage));
			} catch (Exception e) {
				e.printStackTrace();
				musicName = "[获取歌名失败]";
			}
			if (!isRadioModel) {
				tvInfo.setText(musicName);
			}
		} else if (readMessage.startsWith(CMDUtils.MUSIC_TOTAL_TIME_HEAD)) {
			String readMusicTime = CMDUtils.readMusicTime(readMessage);
			tv_total_time.setText(readMusicTime);
			totalTime = CMDUtils.parseTime(readMessage);
		} else if (readMessage.startsWith(CMDUtils.MUSIC_CURR_TIME_HEAD)) {
			String readMusicTime = CMDUtils.readMusicTime(readMessage);
			tv_curr_time.setText(readMusicTime);
			currTime = CMDUtils.parseTime(readMessage);
			updatePosition();
			// 收到当前时间时,表示当前肯定是开机状态
			ivPower.getBackground().setLevel(1);
			// 检查显示信息是否完整
			if (tv_total_time.getText().equals(NULL_TIME) || tvInfo.getText().equals(NULL_VALUE)
				|| tvVol.getText().equals(NULL_VALUE) || tvPlayType.getText().equals(NULL_VALUE)
				|| tvMode.getText().equals(NULL_VALUE)
				|| tvSoundEffect.getText().equals(NULL_VALUE)) {
				// 当显示信息不完整 则发送同步命令获取总时间
				sendMessage(CMDUtils.SYNC);
			}
		}
	}

	/**
	 * 更新进度
	 */
	private void updatePosition() {
		if (currTime > totalTime) {
			seekBar.setProgress(0);
		}
		int position = (int) (((currTime * 1.0f) / totalTime) * 100);
		seekBar.setProgress(position);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return false;
	}

	@Override
	public void onBackPressed() {
		if (roundmenu.isMenuOpen()) {
			roundmenu.closeMenu();
			return;
		}
		confirm();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			if (roundmenu.isMenuOpen()) {
				roundmenu.closeMenu();
			} else {
				roundmenu.openMenu();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/*
	 * 确认退出程序
	 */
	public void confirm() {
		AlertDialog.Builder exitSure = new AlertDialog.Builder(MainActivity.this);
		exitSure.setTitle(R.string.app_name);
		exitSure.setMessage(R.string.close_spp);
		exitSure.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				//清除连接设备记录
				sp.edit().remove(CONNECTING_DEVICE).commit();
				
				MainActivity.this.finish();
			}
		});
		exitSure.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
			}
		});
		exitSure.show();
	}
}
